package com.dongzili.binlog.common.binlogsynchronization;


import com.github.shyiko.mysql.binlog.BinaryLogClient;
import com.github.shyiko.mysql.binlog.event.deserialization.EventDeserializer;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.mysql.cj.jdbc.MysqlDataSource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 监听配置信息
 **/
@Data
@Configuration
@Component
@ConfigurationProperties(prefix = "binlog")
public class BinLogConstants {

    private String serverKey;

    private String host;

    private int port;

    private String username;

    private String passwd;

    private List<String> table;

    @Bean
    public BinaryLogClient binaryLogClient(BinLogConstants binLogConstants) {
        BinaryLogClient client = new BinaryLogClient(binLogConstants.getHost(), binLogConstants.getPort(), binLogConstants.getUsername(), binLogConstants.getPasswd());
        EventDeserializer eventDeserializer = new EventDeserializer();
        //序列化
        eventDeserializer.setCompatibilityMode(EventDeserializer.CompatibilityMode.DATE_AND_TIME_AS_LONG, EventDeserializer.CompatibilityMode.CHAR_AND_BINARY_AS_BYTE_ARRAY);
        client.setEventDeserializer(eventDeserializer);
        client.setThreadFactory(new ThreadFactoryBuilder().setNameFormat("async-sql-runner-%d").setDaemon(true).build());
        return client;
    }

    @Bean
    @Lazy
    public MysqlDataSource mysqlDataSource(BinLogConstants binLogConstants) {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setURL("jdbc:mysql://" + binLogConstants.getHost() + ":" + binLogConstants.getPort());
        mysqlDataSource.setUser(binLogConstants.getUsername());
        mysqlDataSource.setPassword(binLogConstants.getPasswd());

        return mysqlDataSource;
    }


}